/**
 * 实时通信核心类（协议无关层）
 */
export class RealtimeClient {
    constructor(adapter, options = {}) {
        this.adapter = new adapter(options);
        this.listeners = new Map(); // 事件监听器 { event: [callback1, callback2] }
    }

    // 连接服务
    connect() {
        this.adapter.connect({
            onMessage: (data) => this._dispatch('message', data),
            onOpen: () => this._dispatch('open'),
            onClose: () => this._dispatch('close'),
            onError: (err) => this._dispatch('error', err)
        });
    }

    // 发送数据（如果协议支持）
    send(data) {
        if (this.adapter.supportsSend) {
            this.adapter.send(data);
        } else {
            console.warn('当前协议不支持主动发送数据');
        }
    }

    // 断开连接
    disconnect() {
        this.adapter.disconnect();
    }

    // 事件监听
    on(event, callback) {
        if (!this.listeners.has(event)) {
            this.listeners.set(event, []);
        }
        this.listeners.get(event).push(callback);
    }

    // 移除监听
    off(event, callback) {
        const handlers = this.listeners.get(event) || [];
        this.listeners.set(
            event,
            handlers.filter(fn => fn !== callback)
        );
    }

    // 触发事件
    _dispatch(event, ...args) {
        const handlers = this.listeners.get(event) || [];
        handlers.forEach(fn => fn(...args));
    }
}
